package com.tidc.manage.tool;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author innoyiya
 * @date 2018/9/15.
 */
public class JwtUtils {

    private static Algorithm algorithm;

    static {
        try {
            algorithm = Algorithm.HMAC256("secret");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 传入登录账号和最大可用时间
     *
     * @param userId  用户账号
     * @param maxTime 最大可用时间
     * @return 用户的token
     * @throws IllegalArgumentException ？向上抛出？
     * @throws UnsupportedEncodingException 故意抛出的异常
     */
    public static String createToken(String userId, Long maxTime, int level) throws IllegalArgumentException, UnsupportedEncodingException {
        Map<String, Object> map = new HashMap<>(16);
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        return JWT.create().withHeader(map)
                .withClaim("userId", userId)
                .withClaim("level", level)
                .withExpiresAt(new Date(System.currentTimeMillis() + maxTime))
                .sign(algorithm);
    }

    /**
     * 验证token
     *
     * @param token
     * @return
     * @throws TokenExpiredException
     */
    public static DecodedJWT verifyJwt(String token) throws TokenExpiredException {
        DecodedJWT decodedJWT = null;
        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
        decodedJWT = jwtVerifier.verify(token);
        return decodedJWT;
    }
}
